'use strict';

const { Gateway, Wallets } = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const path = require('path');
const { buildCAClient, registerAndEnrollUser } = require('../../test-application/javascript/CAUtil.js');
const { buildCCPOrg1, buildCCPOrg2, buildWallet, prettyJSONString} = require('../../test-application/javascript/AppUtil.js');

const mspOrg1 = 'Org1MSP';
const mspOrg2 = 'Org2MSP';

const myChannel = 'mychannel';
const myChaincodeName = 'myContractTest3';

//查询用户历史订单信息
async function getUserOrders(UserID){
    try {
        const ccp = buildCCPOrg1();
        const walletPath = path.join(__dirname, 'wallet/org1');
        const wallet = await buildWallet(Wallets, walletPath);

        const gateway = new Gateway();

		// Connect using Discovery enabled
		await gateway.connect(ccp,
			{ wallet: wallet, identity: 'admin', discovery: { enabled: true, asLocalhost: true } });

		const network = await gateway.getNetwork(myChannel);
		const contract = network.getContract(myChaincodeName);
        //获取用户信息  提取订单列表
		console.log('\n--> Evaluate Transaction: query the UserOrders');
		var userBuffer = await contract.evaluateTransaction('QueryInfo',UserID);
		console.log('*** Result: user: ' + prettyJSONString(userBuffer.toString()));
        let user = JSON.parse(userBuffer);    
        console.log(user.orders)
        // 提取部分订单信息
        var orderList = []
        for (let order of user.orders){
            let orderBuffer = await contract.evaluateTransaction('QueryInfo',order);
            console.log(orderBuffer.toString())
            let obj = JSON.parse(orderBuffer);    
		    // console.log('*** Result: order: ' + prettyJSONString(orderBuffer.toString()));
            let o = {}
            o.auctionId = obj.auctionId
            o.price = obj.price
            o.amount = obj.amount
            o.time = obj.Time
            if(obj.sellerId.includes(UserID)){
                o.status = "卖家"
            }else{
                o.status = "买家"
            }
            orderList.push(o)
        }
        console.log(orderList)
		gateway.disconnect();
    } catch (error) {
        console.error(`发生错误: ${error}`);
        process.exit(1);
    }
    return orderList;
}
async function main() {

	if (process.argv[2] === undefined && process.argv[3] === undefined && process.argv[4] === undefined) {
		console.log('Usage: node all.js method org userID');
		process.exit(1);
	}
    
	const method = process.argv[2];
	const org = process.argv[3];
	const userId = process.argv[4];

	try {
		if (org === 'Org1' || org === 'org1') {
            if(method === "getUserOrders"){
                console.log("执行 method: getUserOrders..")
                await getUserOrders(userId);
            }else if(method === "trade"){
                console.log("执行 method: trade..")
                await trade(userId);
            }else if(method === "addTradeInfo"){
                    console.log("执行 method: addTradeInfo..")
                    await addTradeInfo(userId);
            }else if(method === "getMeter"){
                console.log("执行 method: getMeter..")
                await getMeter();
        }   else{
                console.log("pass,method 不存在..")
            }
		}
		else {
			console.log('Usage: node all.js method org userID');
			console.log('Org must be Org1');
		}
	} catch (error) {
		console.error(`Error : ${error}`);
		process.exit(1);
	}
}
module.exports = {getUserOrders};
//main();
